import React, { useEffect, useState } from 'react';
import type { FC } from 'react';
import './index.css';
import { LeftOutline } from 'antd-mobile-icons'
import { useNavigate } from 'react-router-dom'
import { Toast } from 'antd-mobile'
import { useChat } from '../../hooks/useChat'
import ChatMessage from '../../compontent/ChatMessage'
import ChatInput from '../../compontent/ChatInput'
import ThinkingIndicator from '../../compontent/ThinkingIndicator'
import FileUpload from '../../compontent/FileUpload'
import FilePreview from '../../compontent/FilePreview'
import type { FileItem } from '../../api/ai'

const Finance: FC = ({ }) => {
  const navigate = useNavigate()
  const [selectedFiles, setSelectedFiles] = useState<FileItem[]>([])

  // 使用聊天hook
  const {
    chatList,
    isLoading,
    messagesEndRef,
    sendMessage,
    sendMessageWithFiles,
    clearChat,
    scrollToBottom,
  } = useChat()

  // 自动滚动到底部
  useEffect(() => {
    scrollToBottom()
  }, [chatList, isLoading, scrollToBottom])

  // 处理文件选择
  const handleFileSelect = async (files: FileList) => {
    try {
      const fileItems: FileItem[] = []

      for (let i = 0; i < files.length; i++) {
        const file = files[i]

        // 验证文件大小（最大10MB）
        if (file.size > 10 * 1024 * 1024) {
          Toast.show(`文件 ${file.name} 过大，最大支持10MB`)
          continue
        }

        // 验证文件类型
        const allowedTypes = [
          'image/jpeg', 'image/png', 'image/gif', 'image/webp',
          'application/pdf', 'text/plain', 'application/json'
        ]

        if (!allowedTypes.includes(file.type) && !file.name.endsWith('.txt')) {
          Toast.show(`不支持的文件类型: ${file.name}`)
          continue
        }

        // 创建文件预览
        let preview = ''
        if (file.type.startsWith('image/')) {
          preview = await new Promise<string>((resolve) => {
            const reader = new FileReader()
            reader.onload = () => resolve(reader.result as string)
            reader.readAsDataURL(file)
          })
        }

        fileItems.push({
          id: `${Date.now()}-${i}`,
          file,
          preview
        })
      }

      setSelectedFiles(prev => [...prev, ...fileItems])
      Toast.show(`已选择 ${fileItems.length} 个文件`)
    } catch (error) {
      console.error('处理文件失败:', error)
      Toast.show('处理文件失败')
    }
  }

  // 移除文件
  const removeFile = (id: string) => {
    setSelectedFiles(prev => prev.filter(item => item.id !== id))
  }

  // 清空文件
  const clearFiles = () => {
    setSelectedFiles([])
  }

  // 发送带文件的消息
  const handleSendWithFiles = async () => {
    if (selectedFiles.length === 0) return

    try {
      const files = selectedFiles.map(item => item.file)
      // 创建FileList对象
      const fileList = {
        ...files,
        item: (index: number) => files[index] || null,
        length: files.length
      } as FileList

      await sendMessageWithFiles('', fileList)
      clearFiles()
    } catch (error) {
      console.error('发送文件失败:', error)
      Toast.show('发送文件失败')
    }
  }

  // 发送文本消息
  const handleSendMessage = async (message: string) => {
    if (selectedFiles.length > 0) {
      // 如果有文件，发送带文件的消息
      try {
        const files = selectedFiles.map(item => item.file)
        // 创建FileList对象
        const fileList = {
          ...files,
          item: (index: number) => files[index] || null,
          length: files.length
        } as FileList

        await sendMessageWithFiles(message, fileList)
        clearFiles()
      } catch (error) {
        console.error('发送消息失败:', error)
        Toast.show('发送消息失败')
      }
    } else {
      // 纯文本消息
      await sendMessage(message)
    }
  }

  return (
    <div className="finance">
      <div className="finance-header">
        <div className="finance-header-left" onClick={() => navigate(-1)}>
          <div className="finance-header-left-icon">
            <LeftOutline width={25} height={25} />
          </div>
        </div>
        <div className="finance-header-center">
          AI健康咨询
        </div>
        <div className="finance-header-right" onClick={clearChat}>
          <span style={{ fontSize: '12px', color: '#666' }}>清空</span>
        </div>
      </div>

      {/* 聊天消息区域 */}
      <div className="chat-container">
        <div className="messages-container">
          {chatList.map((message) => (
            <ChatMessage key={message.id} message={message} />
          ))}
          {isLoading && <ThinkingIndicator />}
          <div ref={messagesEndRef} />
        </div>
      </div>

      {/* 文件预览区域 */}
      {selectedFiles.length > 0 && (
        <FilePreview
          files={selectedFiles}
          onRemove={removeFile}
          onSend={handleSendWithFiles}
          onCancel={clearFiles}
        />
      )}

      {/* 聊天输入区域 */}
      <div className="input-area">
        <div className="input-row">
          <FileUpload
            onFileSelect={handleFileSelect}
            disabled={isLoading}
            accept="image/*,.pdf,.txt,.json"
            multiple={true}
          />
          <ChatInput onSend={handleSendMessage} disabled={isLoading} />
        </div>
      </div>
    </div>
  )
}

export default Finance
